package com.esproject.esFactory;

import com.alibaba.fastjson.JSON;
import com.esproject.esutils.PropertiesHelper;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import io.searchbox.indices.DeleteMapping;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequestBuilder;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

public class ElasticClientFactory {

    //Mapping
    public final static String ES_SNS_OPERATION_MAP =
            "{\"cv_data\":"
                    + "{"
                    + "\"dynamic\":true,"
                    + "\"properties\":"
                    + "{"
                    + "\"college\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"expJob\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"expect_city\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"leastcom\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"leastjob\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"major\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"name\":{\"type\":\"string\",\"index\":\"analyzed\"},"
                    + "\"cuid\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"cvid\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"months\":{\"type\":\"string\",\"index\":\"not_analyzed\"},"
                    + "\"edu\":{\"type\":\"string\",\"index\":\"not_analyzed\"}"
                    + "}"
                    + "}"
                    + "}";
    private ElasticClientFactory() {

    }
    public static Client init() {
        TransportClient  client = null;
        try {
            String path = "es.properties";
            InputStream fs = ElasticClientFactory.class.getClassLoader().getResourceAsStream(path);
            PropertiesHelper p = new PropertiesHelper(fs);
            String clusterName = p.getString("cluster.name");
            String esUrl = p.getString("url");
            String port = p.getString("port");
            if (StringUtils.isBlank(clusterName) || StringUtils.isBlank(esUrl) || StringUtils.isBlank(port)) {
                throw new Exception(path + "conf/es.properties format Exception");
            }
            List<String> urlList = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(esUrl);
            Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
            client = TransportClient.builder().settings(settings).build();
            for (String url : urlList) {
                client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(url), Integer.parseInt(port)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }
    private static class SingelHolder {
        private static Client clientInstance = init();
    }

    /**
     * 单例获取客户端
     * @return
     */
    public static Client getClient(){
        return SingelHolder.clientInstance;
    }

    /**
     * 默认配置创建索引
     * @param indexName
     * @return
     */
    public static boolean createIndex(String indexName){
        Client client = ElasticClientFactory.getClient();
        System.out.println(client);
        CreateIndexRequestBuilder response =client.admin().indices().prepareCreate(indexName);
        CreateIndexResponse createIndexResponse = response.execute().actionGet();
        return createIndexResponse.isAcknowledged();
    }

    /**
     * 带有分片和副本数
     * @param indexName
     * @param numShards
     * @param number_of_replicas
     * @return
     */
    public static boolean createIndex(String indexName,int numShards,int number_of_replicas){
        Map<String,Integer> indexConfig = Maps.newHashMap();
        indexConfig.put("number_of_shards",numShards);
        indexConfig.put("number_of_replicas",number_of_replicas);
        Client client = ElasticClientFactory.getClient();
        CreateIndexRequestBuilder request =client.admin().indices().prepareCreate(indexName).setSettings(indexConfig);
        CreateIndexResponse createIndexResponse = request.execute().actionGet();
        return createIndexResponse.isAcknowledged();
    }

    /**
     * 设置映射
     * @param indeName
     * @param maps
     * @return
     */
    public static boolean putMapping(String indeName,String maps){
        Client client = ElasticClientFactory.getClient();
        System.out.println(client);
        PutMappingRequestBuilder req =client.admin().indices().preparePutMapping(indeName).setType("cv_data").setSource(maps);
        PutMappingResponse putMappingResponse = req.execute().actionGet();
        return putMappingResponse.isAcknowledged();
    }
    /**
     * 删除索引
     * @param indexName
     * @return
     */
    public static boolean deleteIndex(String indexName){
        Client client = ElasticClientFactory.getClient();
        DeleteIndexResponse req = client.admin().indices().prepareDelete(indexName).execute().actionGet();
        return req.isAcknowledged();
    }

    /**
     * 删除索引
     * @param indexName
     * @return
     */
    public static boolean configFreshTime(String indexName){
        Client client = ElasticClientFactory.getClient();
        Map<String,Object> maps = Maps.newHashMap();
        maps.put("index.refresh_interval","1m");
//        ClusterStatsResponse clusterStatsNodeResponses = client.admin().cluster().prepareClusterStats().execute().actionGet();
//        System.out.println(clusterStatsNodeResponses);
        ClusterUpdateSettingsResponse clusterUpdateSettingsResponse = client.admin().cluster().prepareUpdateSettings().setPersistentSettings(maps).execute().actionGet();
        System.out.println(JSON.toJSONString(clusterUpdateSettingsResponse));
        return true;
    }

    public static void main(String[] args) throws UnknownHostException {
      System.out.println(ElasticClientFactory.deleteIndex("cv_info"));
        System.out.println(ElasticClientFactory.createIndex("cv_info",5,0));
       System.out.println(ElasticClientFactory.putMapping("cv_info",ES_SNS_OPERATION_MAP));

       // configFreshTime("cv_info");
    }

}
